<template>
  <el-button
      v-bind="props"
      icon="Delete"
      :disabled="disable"
      @click="handleDelete"
      v-show="props.show"
  >{{props.label}}</el-button>
</template>

<script lang="ts" setup>
import eventBus from '@/event/eventBus';
import {replaceDynamicVar} from '@/api/tool/replacevar'
import {listInterfaceAll,convert2ApiJson,doRequest} from '@/api/business/interface'
import {
  tableRowSelectChangeKey,resetFormKey,executeQueryKey
} from "@/config/app.keys";
import {onMounted, ref, onUnmounted,computed, inject,getCurrentInstance} from "vue";
import {loadingKey, showDialogKey} from "../../../config/app.keys";
import {ElMessage} from "element-plus";
import {formModeKey} from "@/components/form/state.key";
const {proxy} = getCurrentInstance();
interface Props {
  btId?:string//按钮本身id
  label?: string
  size?:string
  type?:string
  plain?:boolean
  text?:boolean
  bg?:boolean
  link?:boolean
  round?:boolean
  circle?:boolean
  loading?:boolean
  disabled?:boolean
  autofocus?:boolean
  formData?:object
  id?:string
  bindComponent?:string//绑定数据源组件 通常为查询按钮，删除后通知它查询
  operationdata:object//操作数据
  research?:boolean
  show?:boolean//是否显示
  mode?: FormFieldMode
}
const props = withDefaults(defineProps<Props>(), {
  label: '删除',
  type:'danger',
  show:true,
})
const ids = ref([]);
const form = ref({});
const disable = ref(false);
const selectRows = ref([]);
const formMode = inject(formModeKey)
const cMode = computed<FormFieldMode>(() => {
  if (props.mode) {
    return props.mode
  }
  if (formMode?.value) {
    return formMode.value
  }
  return "edit"
})
onMounted(() => {
  console.log('mode:'+cMode.value)
  eventBus.$on(props.id+"_"+tableRowSelectChangeKey, (data) => {
    //debugger;
    console.log('tableRowSelectChangeKey:'+JSON.stringify(data))
    disable.value = data.selectRows.length==0
    selectRows.value = data.selectRows
    console.log('selectRows.value1:'+JSON.stringify(selectRows.value));
  })
})
onUnmounted(() => {
  eventBus.$off(props.id+"_"+tableRowSelectChangeKey)
})
/** 更新按钮操作 */
function handleDelete() {
  // 只有在 edit 模式下才执行删除操作
  if (cMode.value !== 'edit') {
    return;
  }

  proxy.$modal.confirm('是否确认删除的数据项？').then(function() {
    for(let i=0;i<selectRows.value.length;i++) {
      callApi(props.operationdata,selectRows.value[i]);
    }
    if (props.research && props.bindComponent) {
      eventBus.$emit(props.bindComponent + "_" +executeQueryKey)
    }
  }).catch(() => {}); // 添加错误捕获

}



/**
 * 调用api接口
 * @param operationdata
 * @param insertFlag
 */
async function callApi(operationdata,row) {
//替换变量值
  let opertionParameter = JSON.stringify(operationdata.parameterList);
  let contextMap = new Map();
  contextMap.set('id',row.id)
  // console.log('props.formData:' + JSON.stringify(props.formData))
  let replaceParameters = replaceDynamicVar(props.formData, contextMap, opertionParameter)

  //将replaceParameters转换为json对象
  let jsonParameters = JSON.parse(replaceParameters);
  //调用API
  //改变装载状态
  eventBus.$emit(props.id + "_" + loadingKey, true);
  //根据接口编码查询接口信息
  let interfaceParam = {"interfaceCode": operationdata.interfaceCode};
  let interfaceInfo = await listInterfaceAll(interfaceParam);
  if (interfaceInfo.code === 200) {
    //调用接口
    let commitParameter = convert2ApiJson(jsonParameters)


    let apiParameter = {...commitParameter};
    //判断接口为get,且不是通用接口时，则拼接到后面
    if (interfaceInfo.data[0].interfaceMethod.toLowerCase() == 'delete') {

      //尝试替换url中的变量
      interfaceInfo.data[0].interfaceUrl = replaceDynamicVar(apiParameter, contextMap, interfaceInfo.data[0].interfaceUrl);
    }
    let res = await doRequest(interfaceInfo.data[0], apiParameter);

    if (res.code === 200) {
      //debugger;
      proxy.$modal.msgSuccess("删除成功");

    } else {
      ElMessage.error(res.msg || '操作失败！')
    }
  }
}

</script>

<style scoped>

</style>
